<template>
  <div class="echart-cont">
    <!--此容器作用在于,防止chart在初始化时撑开弹性容器-->
    <div
      ref="echart"
      class="full"
      :style="{ width: width, height: height }"
    ></div>
  </div>
</template>
<script>
import echarts from "echarts";

if (echarts.version && echarts.version[0] < 4) {
  console.warn("echarts版本过低,请更新代码后运行\n npm update echarts");
}
export default {
  name: "ui-echarts-basics",
  props: {
    // echarts的配置项
    option: {
      type: Object,
      default: _ => {}
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    merge: {
      type: Boolean,
      default: false
    },
    tooltip: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    show() {
      return (
        Array.isArray(this.option.series) &&
        this.option.series.length > 0 &&
        this.option.series[0].data.length > 0
      );
    }
  },
  data() {
    return {
      chart: null, //chart实例
      resizeTimer: null, //resize触发间隔
      init: false,
      config: {},
      target: null,
      autoTip: null
    };
  },
  watch: {
    option: {
      handler(v) {
        if (v && this.show) {
          let sto = setTimeout(() => {
            if (!this.init) {
              this.init = true;
              // 初始化实例
              this.chart = echarts.init(this.$refs["echart"], "light");
              // 如果有配置项,初始就渲染
              this.option && this.chart.setOption(this.option);

              // 点击事件
              this.chart.on("click", params => {
                this.$emit("node-click", params);
              });
            } else {
              // 更新echart
              this.chart.setOption(this.option, {
                notMerge: this.merge, //可选，是否不跟之前设置的option进行合并，默认为false，即合并。
                lazyUpdate: false, //可选，在设置完option后是否不立即更新图表，默认为false，即立即更新。
                silent: false //可选，阻止调用 setOption 时抛出事件，默认为false，即抛出事件。
              });
            }
            clearTimeout(sto);
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    resize() {
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.chart.resize();
        this.resizeTimer = null;
      }, 250);
    }
  },
  mounted() {
    // 绑定window resize
    window.addEventListener("resize", this.resize);

    // 外部告诉echart需要重绘
    this.$on("global:echartResize", this.resize);
  },
  beforeDestroy() {
    // 解绑window resize
    window.removeEventListener("resize", this.resize);

    // 销毁chart实例
    this.chart.clear();
    this.chart.dispose();

    // 销毁监听
    this.$off("global:echartResize", this.resize);
  }
};
</script>
<style lang="scss" scoped>
.echart-cont {
  position: relative;
  width: 100%;
  height: 100%;

  .full {
    position: absolute;
    width: 100%;
    height: 100%;
  }
}
</style>
